from bilibili_api import video, Verify, user
import logging
from mongo import Mongo
from redis_bilibili import RedisBiliBili
import os
import time


logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    filename='updateblibli.txt',
    filemode='a'
)


class BliBli(object):
    def __init__(self, data_id, cf):
        self.verify = Verify(data_id, cf)
        self.M = Mongo()

    def update_video(self, data):
        try:
            # 上传视频
            filename = video.video_upload(data['video_path'], verify=self.verify)
            # 上传封面
            cover_url = video.video_cover_upload(data['img_path'], verify=self.verify)
            send_data = {
                "copyright": 2,
                "source": f"平台: {data['platform']}; UP: {data['name']}; URL: {data['source']}",
                "cover": cover_url,
                "desc": data['desc'],
                "desc_format_id": 0,
                "dynamic": "",
                "interactive": 0,
                "no_reprint": 1,
                "subtitles": {
                    "lan": "",
                    "open": 0
                },
                "tag": data["tag"],
                "tid": data['tid'],
                "title": data['title'],
                "videos": [
                    {
                        "desc": "",
                        "filename": filename,
                        "title": "P1"
                    }
                ]
            }
            # 提交投稿
            result = video.video_submit(send_data, verify=self.verify)

            if result:
                logging.info(f'上传blibli 成功 {data["name"]} {data["title"]} {result}')
                self.M.set_data(data)
                logging.info(f"{data['name']} {data['title']} 以写入")
            else:
                logging.info(f'上传blibli 失败 {data["name"]} {data["title"]} {result}')
        except Exception as e:
            logging.error(f'上传blibli 失败 {data["name"]} {data["title"]} {e}')
        finally:
            time.sleep(60)
            self.rm_video_and_img(data['video_path'], data['img_path'])
        # 成功的话会返回bv号和av号

    def run(self, data):
            self.update_video(data)

    def rm_video_and_img(self, video_path, img_path):
        try:
            os.remove(video_path)
            os.remove(img_path)
        except Exception as e:
            logging.error(str(e))


if __name__ == '__main__':
    B = BliBli(
        data_id="644f4d90%2C1622640694%2Cc83fd*c1",
        cf="10e729f955aa81ba5654c037c80283b2"
    )
    # while True:


